package com.hp.bon.sgw.service;

import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.util.XmlValidatorDef;
import com.hp.bon.sgw.util.XmlValidatorRule;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Path;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Path("/")
public class SGWCapabilityReqXMLValidator
{
  private static SGWCapabilityReqXMLValidator instance;
  private static final Logger logger = LoggerFactory.getLogger(SGWCapabilityReqXMLValidator.class);

  public static SGWCapabilityReqXMLValidator getInstance()
  {
    if (instance == null) {
      instance = new SGWCapabilityReqXMLValidator();
    }
    return instance;
  }

  public int validateRequest(String capability, Element reqEL, StringBuilder hint)
  {
    int SUCCESS = 0;
    XmlValidatorDef validatorDef = (XmlValidatorDef)SpringContext.getInstance().getConfigService().getValiatorDefMap().get(capability);
    if (validatorDef == null) {
      return 0;
    }
    return validatorDef.validateXML(reqEL, hint);
  }

	@SuppressWarnings("unchecked")
	public static Map<String, XmlValidatorDef> parseDefXml(Document document) {
		Map<String, XmlValidatorDef> newValiatorDefs = new LinkedHashMap<String, XmlValidatorDef>();
		Element root = document.getRootElement();
		List<Element> allCapabilityEls = root.elements("capability");
		for (Element capEl : allCapabilityEls) {
			XmlValidatorDef def = new XmlValidatorDef();
			def.capability = capEl.attributeValue("name");
			def.enabled = capEl.attributeValue("enabled", "true").equalsIgnoreCase("true");
			def.validatorRules = parseValidateRules(capEl.elements("rule"));
			if (newValiatorDefs.containsKey(def.capability)) {
				logger.warn("duplicat capabiity validator " + def.capability);
				continue;
			}
			newValiatorDefs.put(def.capability, def);
		}
		return newValiatorDefs;
	}

  private static List<XmlValidatorRule> parseValidateRules(List<Element> elements) {
    if (elements.isEmpty()) {
      return Collections.emptyList();
    }
    List allRules = new ArrayList(elements.size());
    for (Element ruleEL : elements)
    {
      XmlValidatorRule rule = new XmlValidatorRule();
      rule.name = ruleEL.attributeValue("name");
      rule.xpath = ruleEL.elementTextTrim("xpath");
      rule.checker = ruleEL.elementTextTrim("check");
      rule.required = ruleEL.attributeValue("required", "true").equalsIgnoreCase("true");
      String errCode = ruleEL.attributeValue("code");
      if (errCode != null) {
        rule.errCode = Integer.parseInt(errCode);
      }
      allRules.add(rule);
    }
    return allRules;
  }
}